package com.yq.tanhua.ui.userinfo

import androidx.lifecycle.viewModelScope
import com.fmt.mvi.learn.gobal.log
import com.yq.tanhua.net.BaseViewModel
import com.yq.tanhua.net.TanHuaApiService
import com.yq.tanhua.net.bean.UserInfo
import com.yq.tanhua.utils.UserCenter
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

/**
 * @author: user
 * @date: 2023/3/13
 */
class UserInfoViewModel : BaseViewModel() {
    val userInfoUIState = MutableStateFlow(UserInfoVo())

    val userIntent = MutableSharedFlow<UserInfoIntent>()
    val viewIntent = MutableSharedFlow<ViewIntent>()

    init {

        viewModelScope.launch {
            userIntent.collect {
                when (it) {
                    is UserInfoIntent.GetUserInfo -> getUserInfo()
                    is UserInfoIntent.SaveUserInfo -> saveUserInfo()
                    is UserInfoIntent.UpdateNickName -> {
                        userInfoUIState.value = userInfoUIState.value.copy(nickName = it.nickName)
                    }
                    is UserInfoIntent.UpdateBirth -> {
                        userInfoUIState.value = userInfoUIState.value.copy(birthDate = it.birth)
                    }
                    is UserInfoIntent.UpdateAddress -> {
                        userInfoUIState.value = userInfoUIState.value.copy(address = it.address)
                    }
                    is UserInfoIntent.UpdateHead -> {
                        updateHead(it.head)
                    }

                    is UserInfoIntent.UpdateSex -> {
                        userInfoUIState.value = userInfoUIState.value.copy(sex = it.sex)
                    }
                }
            }
        }
    }


    public fun dispatch(userInfoIntent: UserInfoIntent) {
        viewModelScope.launch {
            userIntent.emit(userInfoIntent)
        }
    }

    private fun getUserInfo() {
        launch(
            block = {
                val userInfo = TanHuaApiService.getUserInfo().fullData()
                UserCenter.updateUserInfo(userInfo)
                val sex = if (userInfo.gender == "man") {
                    "男"
                } else {
                    "女"
                }
                userInfoUIState.value = userInfoUIState.value.copy(
                    headImage = userInfo.avatar, nickName = userInfo.nickname,
                    birthDate = userInfo.birthday, sex = sex, address = userInfo.city
                )
                userInfo.log()
            }, error = {
                it.log()
                "xxxxxxxxxxxxx".log()
            }

        )
    }

    private fun updateHead(headPath: String) {

        launch(
            block = {
                val file = File(headPath)
                val body = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val build = MultipartBody.Builder().addFormDataPart("headPhoto", "head.jpg", body)
                    .setType(MultipartBody.FORM)
                    .build()
                val headurl = TanHuaApiService.uploadFile(build.parts[0]).fullData()
                userInfoUIState.value = userInfoUIState.value.copy(headImage = headurl)
                viewIntent.emit(ViewIntent.UploadHead(true))
            }, error = {
                it.log()
                viewIntent.emit(ViewIntent.UploadHead(false))
            }
        )
    }

    private fun saveUserInfo() {
        launch(
            block = {
                val value = userInfoUIState.value
                val userInfo = UserInfo()
                userInfo.avatar = value.headImage
                userInfo.city = value.address
                userInfo.birthday = value.birthDate
                userInfo.gender = if (value.sex == "男") "man" else "woman"
                userInfo.nickname = value.nickName
                val saveUserInfo = TanHuaApiService.saveUserInfo(userInfo).fullData()
                saveUserInfo.log()
                viewIntent.emit(ViewIntent.SaveSuccess)
            },
            error = {
                it.log()
            }
        )
    }
}

sealed class UserInfoIntent {
    object GetUserInfo : UserInfoIntent()
    object SaveUserInfo : UserInfoIntent()
    class UpdateNickName(var nickName: String) : UserInfoIntent()
    class UpdateAddress(var address: String) : UserInfoIntent()
    class UpdateSex(var sex: String) : UserInfoIntent()
    class UpdateBirth(var birth: String) : UserInfoIntent()
    class UpdateHead(var head: String) : UserInfoIntent()
}


sealed class ViewIntent {
    object SaveSuccess : ViewIntent()
    class UploadHead(var isSucess: Boolean) : ViewIntent()
}

data class UserInfoVo(
    var headImage: String? = null,
    var nickName: String = "",
    var birthDate: String = "",
    var sex: String = "",
    var address: String = ""
)